<?php

namespace app\controller\api\module\publics;

use think\exception\ValidateException;
use think\response\Json;

class Index extends \app\controller\api\module\BaseController
{
    /**
     * 账号密码登录
     * @return Json
     */
    public function login(): Json
    {
        $name = values('post.username');
        $pwd = values('post.password');
        try {
            $this->validate([
                'name' => $name,
                'pwd' => $pwd,
            ], [
                'name|账号' => ['require'],
                'pwd|密码' => ['require'],
            ]);
            $name = str_replace(["'", '"', "/", "\\", '#', 'or', 'and', 'null', 'is null', '=', ' '], '', $name);
            $info = Model('user')->getJGInfo('user_compilation', 'user_compilation.uid = user.id', ['user.username' => $name], 'user.id, user.username, user.pwd, user.login_num, user_compilation.score');
            if(!empty($info) and password_verify($pwd, $info['pwd'])){
                $this->updateUserInfo($info);
                $refreshToken = $this->makeRefreshToken($info);
                return responseMsg('登录成功', 200, [
                    'id' => $info['id'],
                    'username' => $info['username'],
                    'score' => $info['score'],
                ], [
                    'token' => $this->makeToken($info, $refreshToken),
                    'refreshtoken' => $refreshToken,
                ]);
            }
            return responseMsg('账号或密码错误');
        }catch (ValidateException $e){
            return responseMsg($e->getError());
        }
    }

    /**
     * 更新用户信息
     * @param $info
     * @return void
     */
    private function updateUserInfo($info){
        $userResult = Model('user')->edit(['id' => $info['id']], [
            'login_num' => $info['login_num'] + 1,
            'last_login_time' => time(),
        ]);
        $userLoginLogResult = Model('userLoginLog')->add([
            'uid' => $info['id'],
            'addtime' => time(),
        ]);
        putLog('/user_something_log/update_user_info_' . date('Ymd') . '.log', json_encode([
            [
                'title' => '用户表信息更新',
                'uid' => $info['id'],
                'status' => $userResult ? '成功' : '失败',
            ],
            [
                'title' => '用户登录日志表信息更新',
                'uid' => $info['id'],
                'status' => $userLoginLogResult ? '成功' : '失败',
            ],
        ]) . PHP_EOL);
    }


    /**
     * 注册
     * @return Json
     */
    public function register(): Json
    {
        $username = values('post.username');
        $pwd = values('post.password');
        $repwd = values('post.repassword');
        try {
            $this->validate([
                'username' => $username,
                'pwd' => $pwd,
                'repwd' => $repwd,
            ], [
                'username|用户名' => ['require', 'max' => 20, 'name' => 'chsAlphaNum'],
                'pwd|密码' => ['require', 'max' => 20],
                'repwd|确认密码' => ['require', 'confirm:pwd'],
            ], ['repwd.confirm' => '两次密码不一致' ]);
            if(Model('user')->getInfo(['username' => $username], 'id')){
                throw new ValidateException('用户名已存在');
            }
            $newID = Model('user')->add([
                'username' => $username,
                'pwd' => password_hash($pwd, PASSWORD_BCRYPT, ['cost' => 12]),
                'createtime' => time(),
                'last_login_time' => time(),
            ], true);
            if($newID){
                Model('userLoginLog')->add([
                    'uid' => $newID,
                    'addtime' => time(),
                ]);
                Model('userCompilation')->add([
                    'uid' => $newID,
                ]);
                $info = Model('user')->getJGInfo('user_compilation', 'user_compilation.uid = user.id', ['user.id' => $newID], 'user.id, user.username, user.pwd, user.login_num, user_compilation.score');
                $refreshToken = $this->makeRefreshToken($info);
                return responseMsg('注册成功', 200, [
                    'id' => $newID,
                    'username' => $username,
                    'score' => $info['score'],
                ], [
                    'token' => $this->makeToken($info, $refreshToken),
                    'refreshtoken' => $refreshToken,
                ]);
            }
            return responseMsg('注册失败');
        }catch (ValidateException $e){
            return responseMsg($e->getError());
        }
    }

}